<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Constants\SendRecordStatusConstants;
use App\CustHub\Model\ChSendRecord;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Config\Annotation\Value;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Mine\Abstracts\AbstractMapper;
use Mine\MineModel;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class ChSendRecordMapper extends AbstractMapper
{
    #[Value('cache.default.prefix')]
    protected string $prefix;

    public function assignModel()
    {
        $this->model = ChSendRecord::class;
    }

    #[Cacheable(prefix: 'ch_send_record',value: 'id_#{id}',ttl: 15 * 60)]
    public function findById(mixed $id): MineModel|Model|string|Builder|null
    {
        return $this->model::query()->where('id',$id)->first();
    }

    /**
     * 获取发送记录列表
     * @param int $taskId
     * @param int $subTaskId
     * @param int $robotId
     * @return array|\Hyperf\Database\Model\Collection
     */
    public function getPendingTasksByTaskId(int $taskId,int $subTaskId,int $robotId): array|\Hyperf\Database\Model\Collection
    {
        return $this->model::query()
            ->where('task_id',$taskId)
            ->when(!empty($subTaskId),function ($query) use ($subTaskId){
                $query->where('sub_task_id',$subTaskId);
            })
            ->where('robot_id',$robotId)
            ->where('status',SendRecordStatusConstants::WAITING)
            ->get();
    }

    /**
     * 获取分页列表
     * @param array $params
     * @return array
     */
    public function getRecordPageList(array $params,$fields = ['*']): array
    {
        $pageSize = $params['page_size'] ?? MineModel::PAGE_SIZE;
        $query = $this->model::query()
            ->select($fields)
            ->with(['contact'=>function ($query) {
                $query->select(['id','nickname','avatar','corp_short_name as corp_name','user_id','is_wechat']);
            },'robot'=>function ($query) {
                $query->select(['id','nickname','avatar','corp_name']);
            }]);
        $data = $this->handleSearch($query,$params)->paginate((int)$pageSize);
        return $this->setPaginate($data);
    }

    public function handlePageItems(mixed $items,array $params): array
    {
        foreach ($items as $item){
            $item->status_text = SendRecordStatusConstants::getMessage($item->status);
            $item->reach_status = $item->status == SendRecordStatusConstants::SUCCESS ? '已触达' : '未触达';
        }
        return $items;
    }

    /**
     * 获取任务下的用户id
     * @param $taskId
     * @return array
     */
    public function getUserIdsByTaskId($taskId,int $type = null): array
    {
        return $this->model::query()
            ->where('task_id',$taskId)
            ->when(!is_null($type),function ($query) use ($type){
                $query->where('type',$type);
            })
            ->pluck('to_id')
            ->toArray();
    }

    /**
     * 删除用户缓存
     * @param mixed $id
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws \RedisException
     */
    public function clearCache(mixed $id): void
    {
        $redis = redis();
        $keyOne = $this->prefix . 'ch_send_record:id_'.$id;
        $redis->del([$keyOne]);
    }

    public function handleSearch(Builder $query, array $params): Builder
    {
        if(isset($params['type']) && filled($params['type'])){
            $query->where('type',$params['type']);
        }

        if(!empty($params['task_id'])){
            if(is_array($params['task_id'])){
                $query->whereIn('task_id',$params['task_id']);
            }else{
                $query->where('task_id',$params['task_id']);
            }
        }

        if(!empty($params['sub_task_id'])){
            $query->where('sub_task_id',$params['sub_task_id']);
        }

        if(!empty($params['robot_id'])){
            $query->where('robot_id',$params['robot_id']);
        }


        if(isset($params['is_processed']) && filled($params['is_processed'])){
            if($params['is_processed'] == 1){
                //已处理
                $query->where('status','<>',SendRecordStatusConstants::WAITING);
            }else{
                //未处理
                $query->where('status',SendRecordStatusConstants::WAITING);
            }
        }

        if(isset($params['status']) && filled($params['status'])){
            if(is_array($params['status'])){
                $statusArr = $params['status'];
                if(isset($statusArr['op'])){
                    $query->where('status',$statusArr['op'],$statusArr['status']);
                }else{
                    $query->whereIn('status',$statusArr);
                }
            }else{
                $query->where('status',$params['status']);
            }

        }

        if(!empty($params['keyword'])){
            $query->whereHas('contact',function ($query) use ($params){
                $query->where('nickname','like','%'.$params['keyword'].'%');
            });
        }

        return $query;
    }
}